package com.tf.mxj.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tf.mxj.entity.EduSubject;
import com.tf.mxj.entity.Excel.SubjectData;
import com.tf.mxj.entity.vo.OneSubject;
import com.tf.mxj.entity.vo.TwoSubject;
import com.tf.mxj.exception.MyException;
import com.tf.mxj.listener.SubjectExcelListener;
import com.tf.mxj.mapper.EduSubjectMapper;
import com.tf.mxj.service.EduSubjectService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject>
        implements EduSubjectService {

    @Override
    public List<OneSubject> getAllOneTwoSubject() {
        // 查询所有一级分类 parent_id = 0
        QueryWrapper<EduSubject> wrapperOne = new QueryWrapper<>();
        wrapperOne.eq("parent_id", "0");
        List<EduSubject> oneSubjectList = baseMapper.selectList(wrapperOne);

        // 查询所有二级分类 parent_id != 0
        QueryWrapper<EduSubject> wrapperTwo = new QueryWrapper<>();
        wrapperTwo.ne("parent_id", "0");
        List<EduSubject> twoSubjectList = baseMapper.selectList(wrapperTwo);

        // 创建最终返回的数据集合
        List<OneSubject> finalSubjectList = new ArrayList<>();

        // 封装一级分类
        for (EduSubject eduSubject : oneSubjectList) {
            OneSubject oneSubject = new OneSubject();
            BeanUtils.copyProperties(eduSubject, oneSubject);

            // 封装二级分类
            List<TwoSubject> twoSubjects = new ArrayList<>();
            for (EduSubject tSubject : twoSubjectList) {
                if (tSubject.getParentId().equals(eduSubject.getId())) {
                    TwoSubject twoSubject = new TwoSubject();
                    BeanUtils.copyProperties(tSubject, twoSubject);
                    twoSubjects.add(twoSubject);
                }
            }
            oneSubject.setChildren(twoSubjects);
            finalSubjectList.add(oneSubject);
        }

        return finalSubjectList;
    }

    @Override
    public void saveSubject(MultipartFile file, EduSubjectService eduSubjectService) {
        try {
            InputStream is = file.getInputStream();
            EasyExcel.read(is, SubjectData.class, new SubjectExcelListener(eduSubjectService))
                    .sheet()
                    .doRead();
        } catch (Exception e) {
            throw new MyException(20001, "Excel 文件读取异常！！");
        }
    }
}